<?php

namespace Api;

use C\L\WebController;
use C\P\QRcode\QRcode;
use C\P\AliyunOSS;
use C\M\User;

class ApiController extends WebController
{
   
    /**
     * 注册接口
     **/
    public function registerAction()
    {
        $mobile   = $this->getValue('mobile', true);
        $password = $this->getValue('password', true);
        $code     = $this->getValue('code', true);
        $tmobile  = $this->getValue('tmobile', false, 'string');
        $imei     = $this->getValue('imei', false, 'string');
        $oaid     = $this->getValue('oaid', false, 'string');

        // 检测是否开启邀请制注册
        $config = $this->s_config->get('other');

        $isEnabledInviteRegister = $config['is_enabled_invite_register'] ?? false;

        if ($isEnabledInviteRegister) {
            if (!$tmobile) {
                return $this->error('请输入邀请人手机号');
            }
            $inviter = User::findByMobile($tmobile);
            if (!$inviter) {
                return $this->error('邀请人手机号错误');
            }
        }

        return $this->s_user->register($mobile, $password, $code, $tmobile, $imei, $oaid)
          ? $this->success()
          : $this->error();
    }

    /**
     * 登录接口
     **/
    public function loginAction()
    {
        $username = $this->getValue('username', true, 'string');
        $password = $this->getValue('password', true);

        return $this->s_user->login($username, $password)
          ? $this->success()
          : $this->error();
    }

    /**
     * 登出接口
     **/
    public function logoutAction()
    {
        $this->ssid->destory();
        $this->success();
    }

    /**
     * 发送验证码接口
     **/
    public function codeAction()
    {
        $mobile = $this->getValue('mobile', true, 'string');
        $type   = $this->getValue('type', true, 'string');

        $this->s_code->send($mobile, $type)
          ? $this->success()
          : $this->error();
    }

    /**
     * 找回密码接口
     **/
    public function forgetpwdAction()
    {
        $username = $this->getValue('username', true);
        $password = $this->getValue('password', true);
        $code     = $this->getValue('code', true);

        return $this->s_user->forgetpwd($username, $password, $code)
          ? $this->success()
          : $this->error();
    }

    /**
     * 心跳包接口
     **/
    public function syncAction()
    {
        $data = [];
        $data['has_new_messages'] = $this->s_message->hasNewMessage($this->uid);
        $this->success($data);
    }

    /**
     * 二维码接口
     **/
    public function qrcodeAction()
    {
        $uid = $this->getValue('uid', true, 'int');

        $user = $this->s_user->search($uid);

        $clientUrl = $this->config->get('config')['client_url'];

        $url = $clientUrl . "/register?m={$user['mobile']}";

        $qrcode = QRcode::png($url, 8, 0);

        $this->response($qrcode);
    }

    public function appAction()
    {
        $app = $this->s_config->get('app');
        $app['web_name'] = $this->s_config->get('web')['title'];
        $app['ad'] = $this->s_config->get('ad');
        $app['web'] = $this->s_config->get('web');
        $this->success($app);
    }

    /**
     * 获取配置文件
     **/
    public function configAction()
    {
        $data = [
            'ssid'             => $this->ssid->register(),
            'ssid_expire_time' => $this->ssid->get('expire_time'),
        ];

        return $this->success($data);
    }

    public function webconfigAction()
    {
        $type = $this->getValue('type', true);

        $config = $this->s_config->get($type);

        return empty($config)
          ? $this->error('未找到相关配置')
          : $this->success($config);
    }

    /**
     * 上传接口
     **/
    public function uploadAction()
    {
        if (!$this->request->hasFiles()) {
            return $this->error('无上传文件');
        }

        $files = $this->request->getUploadedFiles();
        $file = $files[0];

        $config = $this->config->get('oss');
        if (!$config) {
            return $this->error('未配置 OSS');
        }

        $driver = new AliyunOSS(
            $config['access_key_id'],
            $config['access_key_secret'],
            $config['endpoint']
        );

        $fileExtension = $file->getExtension();
        $fileName = strtolower(
            date('YmdHis') .  '_' .  uniqid(null) .  '.' .  $fileExtension
        );

        $filePath = $file->getTempName();

        try {
            $response = $driver->upload(
                $config['bucket'],
                $fileName,
                $filePath
            );

            $data = [
            'file' => $response['info']['url'],
            ];

            return $this->success($data);
        } catch (\Exception $e) {
            return $this->error($e->getMessage());
        }
    }
}
